package com.yuntsg.nnsfcp.util;

import com.yuntsg.nnsfcp.common.utils.StringUtil;
import com.yuntsg.nnsfcp.util.httpclient.HttpClientConfig;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author claud
 * 2018年8月15日18:25:28
 * 抽取的公共的httpclient
 */
public class CommonHttpClient {

    /**
     * 通用的获取html的get方法
     */
    public static String getHtml(BasicCookieStore cookieStore, HttpClientConfig config) {
        System.out.println("当前的地址:" + config.getUrl());
        String html = null;
        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(config.getCredsProvider()).build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse response;
            try {
                httpget = new HttpGet(config.getUrl());
                httpget.setConfig(config.getRequestConfig());
                httpget.addHeader(HttpHeaders.USER_AGENT, HttpClientConfig.USER_AGENT);

                if (!StringUtil.isEmpty(config.getRefer())) {
                    httpget.addHeader(HttpHeaders.REFERER, config.getRefer());
                }
                if (!StringUtil.isEmpty(config.getHost())) {
                    httpget.addHeader(HttpHeaders.HOST, config.getHost());
                }
                httpget.setHeader("cookie", "");


                response = httpClient.execute(httpget);
                int resStatu = response.getStatusLine().getStatusCode();
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "--状态码" + resStatu);
                if (resStatu == HttpStatus.SC_OK) {
                    html = HttpClientUtil.parsingHtml(response);
                    if (html != null) {
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    /**
     * 通用的获取html的post方法
     */
    public static String postHtml(CookieStore cookieStore, Map<String, String> map, HttpClientConfig config) {
        System.out.println("httpclient里面的地址" + config.getUrl());
        String html = "";
        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(config.getCredsProvider()).build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httppost = new HttpPost(config.getUrl());
                List<NameValuePair> nvps = new ArrayList<>();
                if (map != null) {
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                }
                httppost.setEntity(new UrlEncodedFormEntity(nvps, "utf8"));
                httppost.setConfig(config.getRequestConfig());
                httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
                httppost.addHeader(HttpHeaders.USER_AGENT, HttpClientConfig.USER_AGENT);
//                httppost.addHeader("Cookie","LIBUSERSETARTICLESORTCOOKIE=1");
                if (!StringUtil.isEmpty(config.getRefer())) {
                    httppost.addHeader(HttpHeaders.REFERER, config.getRefer());
                }
                if (!StringUtil.isEmpty(config.getHost())) {
                    httppost.addHeader(HttpHeaders.HOST, config.getHost());
                }
                responce = httpClient.execute(httppost);
                int resStatu = responce.getStatusLine().getStatusCode();
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "状态码" + resStatu);
                //获得相应实体
                if (resStatu == HttpStatus.SC_OK) {
                    html = HttpClientUtil.parsingHtml(responce);
                    if (html != null) {
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {
                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }


    /**
     * 通用的获取html的post方法
     */
    public static String postHtmlArray(CookieStore cookieStore, Map<String, String[]> map, HttpClientConfig config) {
        System.out.println("httpclient里面的地址" + config.getUrl());
        String html = "";
        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(config.getCredsProvider()).build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httppost = new HttpPost(config.getUrl());
                List<NameValuePair> nvps = new ArrayList<>();
                if (map != null) {
                    for (Map.Entry<String, String[]> entry : map.entrySet()) {
                        for (int s = 0; s < entry.getValue().length; s++) {
                            nvps.add(new BasicNameValuePair(entry.getKey(),
                                    entry.getValue()[s]));
                        }
                    }
                }
                httppost.setEntity(new UrlEncodedFormEntity(nvps, "utf8"));
                httppost.setConfig(config.getRequestConfig());
                httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
                httppost.addHeader(HttpHeaders.USER_AGENT, HttpClientConfig.USER_AGENT);
                if (!StringUtil.isEmpty(config.getRefer())) {
                    httppost.addHeader(HttpHeaders.REFERER, config.getRefer());
                }
                if (!StringUtil.isEmpty(config.getHost())) {
                    httppost.addHeader(HttpHeaders.HOST, config.getHost());
                }
                responce = httpClient.execute(httppost);
                int resStatu = responce.getStatusLine().getStatusCode();
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "状态码" + resStatu);
                //获得相应实体

                if (resStatu == HttpStatus.SC_OK) {
                    html = HttpClientUtil.parsingHtml(responce);
                    if (html != null) {
                        break;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {
                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    /**
     * 通用的获取pdf的地址
     */
    public static String downloadPdf(CookieStore cookieStore, HttpClientConfig config) {
        String pdfUrl = "";
        System.out.println("httpclient里面的地址" + config.getUrl());
        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(config.getCredsProvider()).build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httpget = new HttpGet(config.getUrl());
                httpget.setConfig(config.getRequestConfig());
                httpget.addHeader(HttpHeaders.USER_AGENT, HttpClientConfig.USER_AGENT);
                if (!StringUtil.isEmpty(config.getRefer())) {
                    httpget.addHeader(HttpHeaders.REFERER, config.getRefer());
                }
                if (!StringUtil.isEmpty(config.getHost())) {
                    httpget.addHeader(HttpHeaders.HOST, config.getHost());
                }
                responce = httpClient.execute(httpget);
                int resStatu = responce.getStatusLine().getStatusCode();
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "状态码" + resStatu);
                if (resStatu == 200) {
                    if (!StringUtil.isEmpty(pdfUrl)) {
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {
                }
                if (e.toString().contains("connect time out")) {
                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return pdfUrl;
    }


    /**
     * 下载pdf的post方法
     * 2018年9月30日13:06:28
     * description:目前在万方医学的账号pdf下载时用到了。
     */
    public static String postDownloadPdf(CookieStore cookieStore, Map<String, String[]> map, HttpClientConfig config) {
        System.out.println("httpclient里面的地址" + config.getUrl());
        String pdfUrl = "";
        for (int i = 1; i <= 2; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httppost = new HttpPost(config.getUrl());
                List<NameValuePair> nvps = new ArrayList<>();
                if (map != null) {
                    for (Map.Entry<String, String[]> entry : map.entrySet()) {
                        for (int s = 0; s < entry.getValue().length; s++) {
                            nvps.add(new BasicNameValuePair(entry.getKey(),
                                    entry.getValue()[s]));
                        }
                    }
                }
                httppost.setEntity(new UrlEncodedFormEntity(nvps, "utf8"));
//                httppost.setConfig(config.getRequestConfig());
                RequestConfig requestConfig = RequestConfig.custom().setRedirectsEnabled(true)
                        .setSocketTimeout(6000).setConnectTimeout(6000).build();
                httppost.setConfig(requestConfig);
                httppost.setHeader("Content-type", "application/x-www-form-urlencoded");
                httppost.addHeader(HttpHeaders.USER_AGENT, HttpClientConfig.USER_AGENT);
                if (!StringUtil.isEmpty(config.getRefer())) {
                    httppost.addHeader(HttpHeaders.REFERER, config.getRefer());
                }
                if (!StringUtil.isEmpty(config.getHost())) {
                    httppost.addHeader(HttpHeaders.HOST, config.getHost());
                }
                responce = httpClient.execute(httppost);
                int resStatu = responce.getStatusLine().getStatusCode();
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "状态码" + resStatu);
                //获得相应实体
                if (resStatu == HttpStatus.SC_OK) {
                    if (!StringUtil.isEmpty(pdfUrl)) {
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {
                }
                if (e.toString().contains("connect time out")) {
                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return pdfUrl;
    }

}
